/****************************************************************************
 * Copyright 2009 Huascar A. Sanchez                                        *
 *                                                                          *
 * Licensed under the Apache License, Version 2.0 (the "License");          *
 * you may not use this file except in compliance with the License.         *
 * You may obtain a copy of the License at                                  *
 *                                                                          *
 *     http://www.apache.org/licenses/LICENSE-2.0                           *
 *                                                                          *
 * Unless required by applicable law or agreed to in writing, software      *
 * distributed under the License is distributed on an "AS IS" BASIS,        *
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. *
 * See the License for the specific language governing permissions and      *
 * limitations under the License.                                           *
 ****************************************************************************/
package com.gotobject.filter.spi;

import com.gotobject.filter.internal.ToStrings;
import static com.gotobject.filter.internal.ToStrings.str;
import static com.gotobject.filter.internal.Pair.of;

import java.util.Map;
import java.util.concurrent.atomic.AtomicReference;

/**
 * @author huascar.sanchez@gmail.com (Huascar A. Sanchez)
 */
public class Variant<V> {
    private final AtomicReference<String> key;
    private final AtomicReference<V>      value;
    private Variant(){
        key   = new AtomicReference<String>();
        value = new AtomicReference<V>();
    }
    
    
    public static <V> Variant<V> copy(Variant<V> that){
        final Variant<V> t = new Variant<V>();
        final String key   = that.key();
        final V      value = that.value();
        t.place(key, value);
        return t;
    }

    public static <V> Variant<V> empty(){
        return new Variant<V>();
    }
    
    public String key(){
        return key.get();
    }

    public Variant place(String k, V v){
        key.compareAndSet(key.get(), k);
        value.compareAndSet(value.get(), v);
        return this;
    }

    public boolean same(String key){
        return key().equals(key);
    }

    @Override
    public String toString() {
        return ToStrings.toString(
                this, 
                of("key", key.get()), 
                of("value", str(value.get()))
        );
    }

    public V value(){
        return value.get();
    }
}
